//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useState, useEffect } from "react";
import type { VoteInfo } from "@/api/project_issue";
import { list_vote, set_vote, remove_vote } from "@/api/project_issue";
import { request } from "@/utils/request";
import { Button, Checkbox, Descriptions, Input, InputNumber, List, message, Popover, Space } from "antd";
import UserPhoto from "@/components/Portrait/UserPhoto";
import { MoreOutlined } from "@ant-design/icons";
import { ProjectInfo } from "@/api/project";
import { get_session } from "@/api/user";

interface IssueVotePanelProps {
    projectInfo: ProjectInfo;
    myUserId: string;
    myDisplayName: string;
    myLogoUri: string;
    issueId: string;
}

const IssueVotePanel = (props: IssueVotePanelProps) => {

    const [myVoteInfo, setMyVoteInfo] = useState<VoteInfo | null>(null);
    const [voteInfoList, setVoteInfoList] = useState<VoteInfo[]>([]);
    const [hasChange, setHasChange] = useState(false);

    const loadVoteInfoList = async () => {
        const sessionId = await get_session();
        const res = await request(list_vote({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            issue_id: props.issueId,
        }));
        const myTmpInfo = res.vote_list.find(item => item.vote_user_id == props.myUserId);
        if (myTmpInfo !== undefined) {
            setMyVoteInfo(myTmpInfo);
        } else {
            setMyVoteInfo({
                vote_id: "",
                basic_info: {
                    estimate_minutes: 0,
                    important: false,
                    urgency: false,
                    extra_desc: "",
                },
                time_stamp: 0,
                vote_user_id: props.myUserId,
                vote_display_name: props.myDisplayName,
                vote_logo_uri: props.myLogoUri,
            });
        }
        setVoteInfoList(res.vote_list.filter(item => item.vote_user_id != props.myUserId));
    };

    const setVote = async () => {
        const sessionId = await get_session();
        if (myVoteInfo == null) {
            return;
        }
        await request(set_vote({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            issue_id: props.issueId,
            vote: myVoteInfo.basic_info,
        }));
        setHasChange(false);
        await loadVoteInfoList();
        message.info("保存成功");
    };

    const removeVote = async () => {
        const sessionId = await get_session();
        if (myVoteInfo == null || myVoteInfo.vote_id == "") {
            return;
        }
        await request(remove_vote({
            session_id: sessionId,
            project_id: props.projectInfo.project_id,
            issue_id: props.issueId,
            vote_id: myVoteInfo.vote_id,
        }));
        setHasChange(false);
        await loadVoteInfoList();
        message.info("清除成功");
    };

    useEffect(() => {
        loadVoteInfoList();
    }, [props.issueId]);

    return (
        <div>
            {myVoteInfo != null && (
                <Descriptions title={<div style={{ marginTop: "10px" }}>我的评估</div>} bordered labelStyle={{ width: "100px" }} extra={
                    <Space style={{ marginRight: "10px" }}>
                        <Button type="primary" disabled={!hasChange}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setVote();
                            }}>保存评估</Button>
                        <Popover placement="bottom" trigger={"click"} content={
                            <Space direction="vertical">
                                <Button type="link" disabled={myVoteInfo.vote_id == ""} danger
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        removeVote();
                                    }}>清除评估</Button>
                            </Space>
                        }>
                            <MoreOutlined />
                        </Popover>
                    </Space>
                }>
                    <Descriptions.Item label="预估时间">
                        <InputNumber value={myVoteInfo.basic_info.estimate_minutes / 60} controls={false} min={0} max={16} precision={1}
                            style={{ width: "150px" }} onChange={value => {
                                setMyVoteInfo({
                                    ...myVoteInfo,
                                    basic_info: {
                                        ...myVoteInfo.basic_info,
                                        estimate_minutes: Math.round((value ?? 0) * 60),
                                    }
                                });
                                setHasChange(true);
                            }} addonAfter="小时" />
                    </Descriptions.Item>
                    <Descriptions.Item label="重要">
                        <Checkbox checked={myVoteInfo.basic_info.important} onChange={e => {
                            e.stopPropagation();
                            setMyVoteInfo({
                                ...myVoteInfo,
                                basic_info: {
                                    ...myVoteInfo.basic_info,
                                    important: e.target.checked,
                                },
                            });
                            setHasChange(true);
                        }} />
                    </Descriptions.Item>
                    <Descriptions.Item label="紧急">
                        <Checkbox checked={myVoteInfo.basic_info.urgency} onChange={e => {
                            e.stopPropagation();
                            setMyVoteInfo({
                                ...myVoteInfo,
                                basic_info: {
                                    ...myVoteInfo.basic_info,
                                    urgency: e.target.checked,
                                },
                            });
                            setHasChange(true);
                        }} />
                    </Descriptions.Item>
                    <Descriptions.Item label="备注" span={3}>
                        <Input.TextArea autoSize={{ minRows: 3, maxRows: 3 }} value={myVoteInfo.basic_info.extra_desc} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setMyVoteInfo({
                                ...myVoteInfo,
                                basic_info: {
                                    ...myVoteInfo.basic_info,
                                    extra_desc: e.target.value,
                                },
                            });
                            setHasChange(true);
                        }} />
                    </Descriptions.Item>
                </Descriptions>
            )}
            {voteInfoList.length > 0 && (
                <List rowKey="vote_id" dataSource={voteInfoList} pagination={false}
                    style={{ height: "calc(100vh - 520px)", overflowY: "scroll" }}
                    renderItem={item => (
                        <List.Item>
                            <Descriptions bordered labelStyle={{ width: "100px" }} style={{ width: "100%" }}
                                title={
                                    <Space>
                                        <UserPhoto logoUri={item.vote_logo_uri} style={{ width: "20px", borderRadius: "10px" }} />
                                        {item.vote_display_name}
                                    </Space>
                                }>
                                <Descriptions.Item label="预估时间">
                                    {(item.basic_info.estimate_minutes / 60).toFixed(1)}小时
                                </Descriptions.Item>
                                <Descriptions.Item label="重要">
                                    {item.basic_info.important ? "是" : "否"}
                                </Descriptions.Item>
                                <Descriptions.Item label="紧急">
                                    {item.basic_info.urgency ? "是" : "否"}
                                </Descriptions.Item>
                                <Descriptions.Item label="备注" span={3}>
                                    <pre style={{ whiteSpace: "pre-wrap", wordWrap: "break-word" }}>{item.basic_info.extra_desc}</pre>
                                </Descriptions.Item>
                            </Descriptions>
                        </List.Item>
                    )} />
            )}
        </div>
    );
};

export default IssueVotePanel;